<template>
  <lay-card style="height:100%;width: 350px">
    <lay-row space="20">
      <lay-col md="20">
        <lay-input
            v-model="scene_name"
            :allow-clear="true"
            size="sm"
            placeholder="请输入查询，区分大小写"
            @change="filterSceneTree"
        >
          <template #suffix>
            <lay-icon type="layui-icon-search" @click="filterSceneTree" size="sm"></lay-icon>
          </template>
        </lay-input>
      </lay-col>
    </lay-row>
    <lay-row space="20">
      <lay-col md="24">
        <lay-line @click="refreshScenes">
          <span>仿真场景</span>
          <lay-icon type="layui-icon-refresh-one" size="sm" style="margin-left: 5px"></lay-icon>
        </lay-line>
        <lay-scroll :height="scrollHeightSource" style="width: 650px">
          <lay-tree
            v-model:data="data"
            :tail-node-icon="tailFlag"
            height="100%"
            v-model:expandKeys="expandKeys"
            :checkStrictly="true"
            :onlyIconControl="onlyIconControl"
            :showLine="showLine"
            :showCheckbox="showCheckbox"
            style="max-width: 350px"
          >
            <template #title="{ data }">
              <lay-row space="10">
                <lay-col md="24">
                  <a @click="handleClick(data)" style="margin-left: 3px">
                    <lay-icon
                      type="layui-icon-component"
                      size="sm"
                      v-if="data.type==='scene_dir'"
                      style="color: royalblue;font-size: 12px"
                    ></lay-icon>
                    <lay-icon
                        type="layui-icon-file-b"
                        size="sm"
                        v-if="data.type==='scene_id'"
                        style="color: turquoise"
                    ></lay-icon>
                    <lay-icon
                        type="layui-icon-list"
                        size="sm"
                        v-if="data.type==='scene_group'"
                        style="color: #51e33b"
                    ></lay-icon>
                    <span>{{data.title}}</span>
                  </a>
                  <lay-icon
                    type="layui-icon-addition"
                    v-if="data.type === 'scene_root'"
                    @click="editNode('add', data)"
                    style="margin-left: 10px"
                  ></lay-icon>
                  <lay-dropdown trigger="hover" updateAtScroll>
                    <lay-icon
                      type="layui-icon-more"
                      v-if="data.type === 'scene_id' || data.type === 'scene_dir' || data.type === 'scene_group'"
                      style="margin-left: 5px"
                    ></lay-icon>
                    <template #content>
                      <lay-card>
                        <lay-row space="10" v-if="data.type === 'scene_id'">
                          <lay-col md="22">
                            <lay-dropdown-menu-item @click="viewRecord(data)">
                              <lay-icon type="layui-icon-log"></lay-icon>查看记录
                            </lay-dropdown-menu-item></lay-col>
                        </lay-row>
                        <lay-row space="10" v-if="data.type === 'scene_dir'">
                          <lay-col md="22">
                            <lay-dropdown-menu-item @click="editNode('add', data)">
                              <lay-icon type="layui-icon-add-circle"></lay-icon>新增
                            </lay-dropdown-menu-item></lay-col>
                        </lay-row>
                        <lay-row space="10">
                          <lay-col md="22">
                            <lay-dropdown-menu-item @click="editNode('update', data)">
                              <lay-icon type="layui-icon-edit"></lay-icon>更新
                            </lay-dropdown-menu-item>
                          </lay-col>
                        </lay-row>
                        <lay-row space="10">
                          <lay-col md="22">
                            <lay-dropdown-menu-item @click="deleteNode(data)">
                              <lay-icon type="layui-icon-delete"></lay-icon>删除
                            </lay-dropdown-menu-item>
                          </lay-col>
                        </lay-row>
                      </lay-card>
                    </template>
                  </lay-dropdown>
                </lay-col>
              </lay-row>
            </template>
          </lay-tree>
        </lay-scroll>
      </lay-col>
    </lay-row>
  </lay-card>
</template>

<script lang="ts">
export default {
    name: 'ScenesTree'
}
</script>

<script lang="ts" setup>
import {h, onBeforeMount, onBeforeUnmount, reactive, ref} from 'vue';
import {layer} from "@layui/layui-vue";
import AddSceneType from "./AddSceneType.vue";
import router from "../../../router";
import {deleteSceneApi, queryScenesApi} from "../../../api/module/scene";
import {TreeService} from "../../../store/databases/TreeService";
import {TreeNode} from "../../../store/databases/TreeNode";
import {notify} from "../../../untils/tip";

const sceneTree = new TreeService();

const {showCheckbox} = defineProps({
  showCheckbox: {type: Boolean, default: ref(false)}
});


onBeforeMount(() => {
  queryTreeScenes();
});

const scrollHeightSource = ref('680px');
const onlyIconControl = ref(true);
const showLine = ref(false);
const tailFlag = ref(false);
const scene_name = ref('');

const msg_id = ref();

// 场景树 列表
const data : any = ref([]);
const expandKeys = ref([]);

// 记录展开的数组
const setExpandNode = () => {
  const sceneTreeExpend = localStorage.getItem('sceneTreeExpend');
  if(sceneTreeExpend){
    expandKeys.value = JSON.parse(sceneTreeExpend);
  }
};

const refreshScenes = () => {
    localStorage.setItem('sceneTreeExpend', JSON.stringify(expandKeys.value));
    queryTreeScenes();
}

const queryTreeScenes = async () => {
  data.value = [];
  sceneTree.clearTree();
  let {result, status, message} = await queryScenesApi();
  if(status === 'success'){
    data.value = result;
    sceneTree.addRawData(result);
    setExpandNode();
  }else {
    notify(status, message);
  }
};

const viewRecord = (node: any) => {
  const params = reactive({scene_id: node.id});
  router.push({name: 'viewRecord', params: params});
};

const handleClick = (node: any) => {
  console.log(node)
  const params = reactive({scene_id: node.id});
  console.log(params)
  switch (node.type) {
    case 'scene_id' :
      router.push({name: 'EditScene', params: params});
      break;
    case 'scene_dir':
      router.push({name: 'SceneList', params: params});
      break;
    case 'scene_group':
      router.push({name: 'SceneList'});
      break;
    default :
      router.push({name: 'NonePage'});
      break;
  }
};

const editNode = (oper: string, node: any) => {
  msg_id.value = layer.open({
    title: "编辑目录/场景的名称",
    area: ['400px','200px'],
    content: h(AddSceneType, {
      operate: oper,
      currentNode: reactive({id: node.id, type: node.type, title: node.title, children: []}),
      updateNode: function (res: any) {
        if(oper === 'add'){
          node.children.push(res);
          sceneTree.addNode(node.id, res);
          console.log(node)
        }else {
          node.title = res.title;
          sceneTree.updateNode(node.id, res);
        }
        layer.close(msg_id.value);
      }
    }),
  })
};

const filterSceneTree = () => {
  if(scene_name.value !== ''){
    const newTrees: any = sceneTree.filterTree(data.value[0],
      (node: TreeNode)=>{return node.title.includes(scene_name.value);})
    data.value = [newTrees]
  }else {
    data.value = sceneTree.getTree();
  }

};

const clearAndGetScenes = () => {
  data.value = []
  data.value = sceneTree.getTree();
};

const deleteSceneNode = async (node: any) => {
  console.log('deleteSceneNode:')
  console.log(node)
  let {result, status, message} = await deleteSceneApi({id: node.id, type: node.type})
  if(status === 'success'){
    let parentNode = node.parentNode;
    console.log(parentNode)
    // 新增加后节点前端挂上去的，与从后台查询的稍有区别。此类直接删除会有异常，无法移除；故去请求一次后台数据刷新
    if(parentNode){
      const index = parentNode.children.indexOf(node);
      parentNode.children.splice(index, 1);
    }else {
      await queryTreeScenes();
    }
  }
  layer.msg(message);
};

const deleteNode = (node: any) => {
  console.log('deleteNode')
  console.log(node)
  if(node.children.length > 0){
    layer.msg('存在不允许删除')
  }else {
    layer.confirm('确认要删除该节点么？', {
      btn: [
        {text:'确认', callback: (id: any) => {
          deleteSceneNode(node);
          layer.close(id); }
        },
        {text:'取消', callback: (id: any) => {
          layer.close(id);}
        }
      ]
    })
  }
};

// 页面销毁前保存当前场景数状态
onBeforeUnmount(()=>{
  localStorage.setItem('sceneTreeExpend', JSON.stringify(expandKeys.value))
});
</script>

<style>
.layui-tree-iconClick >.layui-icon-file{
  display: none;
  width: 1px;
}
</style>